<?php
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
session_start();
$UserName = $_SESSION['UserName'];
$UserID = $_SESSION['ID'];
$bid = $_SESSION['bid'];
$title = $_SESSION['title'];
$status = $_POST['booked'];
$DateToday = date("Y-m-d");
include_once('Mysql_connect.inc');//启动连接，连接名：$conn
if ($status == 'booked') {
    $result_booked0 = mysqli_query($conn, "SELECT roll_id, bid FROM bookingrecord where bid ='$bid'");
    $j = mysqli_num_rows($result_booked0);
    if ($j >= 3) {
        echo "此书已经被预定完";
    }
    else {
        $result_booked = mysqli_query($conn, "SELECT roll_id, bid FROM bookingrecord where roll_id ='$UserID'");
        $rowborrowed = mysqli_fetch_array($result_booked);
        if($rowborrowed['bid'] == $bid) {
            echo "你已经预定此书";
        }
        else {
            $i = mysqli_num_rows($result_booked);
            if ($i <= 2) {
                $result_booked1 = mysqli_query($conn,"insert into bookingrecord (bid, roll_id, name, title, booked_date) values
                            ( '$bid', '$UserID','$UserName','$title','$DateToday')");
                if ($result_booked1) {
                    echo "预订成功";
                }
                else{
                    echo "You cant Booked this book";
                }
            }
            else {
                echo "你已经预定3本书了";
            }
        }
    }
}
else {
    $result_borrowed = mysqli_query($conn, "SELECT bid, roll_id, borrowed_date, return_date FROM bookborrower where roll_id ='$UserID' AND bid ='$bid'");

    if (mysqli_num_rows($result_borrowed)<=0){
        echo "你没有借阅此书";
    }
    else {
        $row = mysqli_fetch_array($result_borrowed, MYSQLI_ASSOC);
        echo $row['roll_id'];
        $BorrowedDate = $row['borrowed_date'];
        $ReturnDate = $row['return_date'];
        $DT3=substr($DateToday,8,2); //日
        $DT2=substr($DateToday,5,2); //月
        $DT1=substr($DateToday,0,4); //年
        $NewReturnDate = date( "Y-m-d", mktime(0,0,0,$DT2,$DT3+60,$DT1));
        if ($NewReturnDate == $ReturnDate) {
            echo "你已经不能续借此书了";
        }
        else {
            $result_borrowed1 = mysqli_query($conn,"UPDATE bookborrower SET return_date ='$NewReturnDate' WHERE bid = '$bid' AND roll_id = '$UserID'");
            if (!$result_borrowed1){
                echo "续借失败，请重新尝试操作";
            }
            else { echo "续借成功，你可以选择退出";
            }
        }
    }
}
unset($_SESSION['bid']);
unset($_SESSION['title']);
include_once('Mysql_unconnect.inc'); //断开连接
?>
